﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Intorise.Common;
using System.Threading.Tasks;

namespace Model
{
    public class SaveCompleteHelper
    {
        static List<FinishedAccount> finishedAccounts = new List<FinishedAccount>();

        static SaveCompleteHelper()
        {
            if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + "已完成.txt"))
            {
                using (StreamReader reader = new StreamReader(AppDomain.CurrentDomain.BaseDirectory + "已完成.txt"))
                {
                    while (!reader.EndOfStream)
                    {
                        var text = reader.ReadLine();
                        var items = text.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                        if (items.Length == 2)
                        {
                            finishedAccounts.Add(new FinishedAccount { Account = items[0], ServerID = items[1] });
                        }
                    }
                }
            }
        }
        public static bool Finished(string account, string serverID)
        {
            lock (finishedAccounts)
            {
                return finishedAccounts.Contains(new FinishedAccount { Account = account, ServerID = serverID });
            }
        }

        public static void SaveFinished(string account, string serverID)
        {
            Task.Factory.StartNew(() =>
            {
                try
                {
                    finishedAccounts.Add(new FinishedAccount { Account = account, ServerID = serverID });
                    using (StreamWriter writer = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "已完成.txt", true))
                    {
                        writer.WriteLine(account + "," + serverID);
                        writer.Flush();
                    }
                }
                catch (Exception ex)
                {
                    ConsoleBLL.WriteLineError("写入已完成账号时出错：");
                    ConsoleBLL.WriteLineError(ex.Message);
                    ConsoleBLL.WriteLineError(ex.StackTrace);
                }
            });
        }
    }

    public class FinishedAccount
    {
        public string Account { get; set; }
        public string ServerID { get; set; }
        public override bool Equals(object obj)
        {
            FinishedAccount account = obj as FinishedAccount;
            if (account != null)
            {
                return account.Account.Equals(this.Account) & account.ServerID.Equals(this.ServerID);
            }
            return false;
        }
    }
}
